package com.example.mybaties.testone.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * DES加解密的工具类
 */
public class DesUtil {

    private static String KEY_STR = "myKey";

    private static Key key;

    private static String CHARSET = "UTF-8";

    static {
        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
            keyGenerator.init(new SecureRandom(KEY_STR.getBytes()));
            key = keyGenerator.generateKey();
            keyGenerator = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取加密的字符串
     */
    public static String getEncyptString(String str) {
        BASE64Encoder base64Encoder = new BASE64Encoder();
        try {
            byte[] strBytes = str.getBytes(CHARSET);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] encryptStrBytes = cipher.doFinal(strBytes);
            return base64Encoder.encode(encryptStrBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密
     */
    public static String getDecyptString(String encryptStr) {
        BASE64Decoder base64Decoder = new BASE64Decoder();
        try {
            byte[] encryptStrBytes = base64Decoder.decodeBuffer(encryptStr);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] strBytes = cipher.doFinal(encryptStrBytes);
            return new String(strBytes, CHARSET);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
